//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 周先生 on 15/11/11.
//  Copyright © 2015年 周先生. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
class OAuthViewController: UIViewController {

    //定义一个webview
    let webView = UIWebView()
    override func loadView() {
        view = webView
        //设置代理
        webView.delegate = self

        print(view)
        print("haha")
    }
    //监听方法
   @objc private func close() {
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    //自动填充
    @objc private func fullAccount() {
        let jsString = "document.getElementById('userId').value = '13693511619' , document.getElementById('passwd').value = 'zgj1989';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    //加载网页
    private func loadOauthPage() {

        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //调用setupUI
        setupUI()
        print(view)
        print("ehehe")
        loadOauthPage()
    }
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    //设置UI界面
    private func setupUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
        
    }
}

//准备处理uiwebview的多有协议方法
extension OAuthViewController: UIWebViewDelegate {
    /*Optional(https://api.weibo.com/oauth2/authorize?client_id=4183572679&redirect_uri=http://www.itcast.cn)
    Optional(http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=6KeZpR&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D4183572679%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D)
    Optional(http://m.weibo.cn/reg/index?jp=1&wm=4406&appsrc=6KeZpR&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D4183572679%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D)
    Optional(https://api.weibo.com/oauth2/authorize?client_id=4183572679&redirect_uri=http://www.itcast.cn)
*/
    
    /*
    Optional(https://api.weibo.com/oauth2/authorize?client_id=4183572679&redirect_uri=http://www.itcast.cn)
    Optional(https://api.weibo.com/oauth2/authorize)
    Optional(https://api.weibo.com/oauth2/authorize#)
    Optional(https://api.weibo.com/oauth2/authorize)
    Optional(http://www.itcast.cn/?code=09a3e829316c3cb7e9321ac94c50e48a)//不希望能够加载出来
    Optional(about:blank)
    Optional(about:blank)
    Optional(about:blank)

    
    
    */
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //协议方法 如果返回bool 返回true表示当前对象可以正常工作 返回false表示不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else {
        return false
        }
        //网页请求页面  或者网页授权界面
        if urlString.hasPrefix("https://api.weibo.com") {
        return true
        }
        if !urlString.hasPrefix(redirect_uri) {
        
        return false
        }
        
        //程序走到这里 一定包含了回到的  url
        guard let query = request.URL?.query else{
        
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        print("12345")
        print(codeStr)
        print(code)
        //调用loadAccessToken
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            
            print("come   here")
            self.dismissViewControllerAnimated(true, completion: nil)
            //发出页面切换的通知
            //moadl出来的页面  需要立即切换页面并且dismiss  需要在dismiss完成后的闭包中 开始页面的切换
            NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewController, object: "Welcome")
        }
        
        return false
    }
    //获取用户token
 
    //加载用户信息

}





